<template>
  <InputForm @register="registerInputForm" @close="handleClose" @success="handleSuccess"/>
</template>
<script lang="ts" name="PermissionApply" setup>
import { onMounted, onUnmounted, ref } from 'vue';
import pubsub from "pubsub-js"
import { useGo } from "/@/hooks/web/usePage"
import { useModal } from "/@/components/Modal"
import { PageEnum } from '/@/enums/pageEnum';
import InputForm from '/@/views/system/permApproval/ApplyForm.vue';
const isOpen = ref<boolean>(false)
const readyApplyList = ref<object[]>([])
const go = useGo()
const [registerInputForm, { openModal: openInputForm }] = useModal();
onMounted(() => {
  pubsub.subscribe("permApply", (msg, data) => {
    console.log('接收权限申请事件, data: ', data)
    if (isOpen.value) {
      const applyList = [ ...readyApplyList.value, data ]
      applyList.forEach(item => pubsub.publish("addPermApply", { ...item }))
      return
    }
    console.log('预备权限申请列表', readyApplyList.value)
    openInputForm(true, { record: { apiResourceUrls: [data.url, ...readyApplyList.value.map(e => e.url)] }, isUpdate: false });
    isOpen.value = true
  })

  // 去申请权限
  pubsub.subscribe("goPermApplyPage", (msg, data) => {
    go(PageEnum.PERM_APPROVAL_APPLY)
  })

  // 预备权限申请, 比如一个页面同时发起多个请求, 请求拦截中只会弹出一个弹框, 只会拦截的请求都会发出事件
  pubsub.subscribe("readyPermApply", (msg, data) => {
    console.log('接收预备权限申请', data)
    if (isOpen.value) {
      pubsub.publish("addPermApply", { ...data })
      return
    }
    readyApplyList.value = Array.from(new Set([...readyApplyList.value, data]))
  })

})

onUnmounted(() => {
  pubsub.unsubscribe("permApply")
  pubsub.unsubscribe("goPermApplyPage")
  pubsub.unsubscribe("readyPermApply")
})
  
const handleClose = () => {
  isOpen.value = false
  readyApplyList.value = []
  pubsub.publish("permApplyClose", {})
}

const handleSuccess = () => {
  isOpen.value = false
  readyApplyList.value = []
  pubsub.publish("permApplySuccess", {})
}
</script>

<style lang="less" scope>
.apply-resource {
  text-align: left;
  border: 1px;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  margin-left: 12px;
  text-overflow: ellipsis;
}
</style>
